package servlet;

import java.io.IOException;
import java.sql.Date;
import java.text.ParseException;
import java.util.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import service.*;
import util.*;

import domain.Actor;
import domain.User;
import ex.DatabaseException;
import ex.RegistrationFailedException;


public class Register extends HttpServlet {
	UserService userService=new UserService();
	ActorService actorService=new ActorService();
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		
		
		List<Title> titles=TitleUtil.getTitles();
		request.setAttribute("titles",titles);
		
		RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/user/register.jsp");
		 if (dispatcher != null) dispatcher.forward(request, response);
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try{
			String firstName=request.getParameter("firstname");
			String surname=request.getParameter("surname");
			String email=request.getParameter("email");
			String password=request.getParameter("password");
			String password2=request.getParameter("password2");
			boolean	female=!request.getParameter("gender").equalsIgnoreCase("male");
			//String image=request.getParameter("image");
			String imageURL=request.getParameter("imageURL");			
			Date birthDate=getDate(request, response);
			String city=request.getParameter("city");
			String tel=request.getParameter("tel");
			String description=request.getParameter("description");
			
			Actor actor = null;
			//storing what titles the user has marked through bitwise operation
			int titleBits = getTitleBits(request, response);
			if(titleBits!=-1){
				
				boolean actorSelected=(titleBits & TitleUtil.actor_bit)==TitleUtil.actor_bit;
				
				if(actorSelected){
					String heightString=request.getParameter("height");
					int height=0;
					if(!RegexUtil.isParsableToInt(heightString)){
						throw new RegistrationFailedException("Height is not in correct format!");
					}
					else{
						height=Integer.parseInt(heightString);
					}
					String weightString=request.getParameter("weight");
					int weight=0;
					if(!RegexUtil.isParsableToInt(weightString)){
						throw new RegistrationFailedException("Weight is not in correct format!");
					}
					else{
						weight=Integer.parseInt(weightString);
					}
					String hairColor=request.getParameter("hair");
					String skinColor=request.getParameter("skin");
					String eyeColor=request.getParameter("eyes");
					actor=new Actor(-1, hairColor, eyeColor,skinColor, height, weight);
				}
			}
			User user=new User((long)-1,email,password,firstName,surname,birthDate, imageURL,description,city,tel, titleBits, 0, 0, actor,true, true, female);
			userService.createUser(user,password2);
			user= userService.authenticateUser(user.getEmail(), user.getPassword());
	
			HttpSession session = request.getSession();
			session.setAttribute("user", user);
			
			response.sendRedirect("user?who=me");
		}
		catch (RegistrationFailedException e) {
			request.setAttribute("registerError", e.getMessage());
			RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/user/register.jsp");
			if (dispatcher != null) dispatcher.forward(request, response);
		}
		catch (DatabaseException e) {
			request.setAttribute("registerError", e.getMessage());
			RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/user/register.jsp");
			if (dispatcher != null) dispatcher.forward(request, response);
		}
		catch (ParseException e) {
			request.setAttribute("registerError", e.getMessage());
			RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/user/register.jsp");
			if (dispatcher != null) dispatcher.forward(request, response);
		}
		catch (Exception e) {
			request.setAttribute("registerError", "A general error occured:" + e.getMessage());
			RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/user/register.jsp");
			if (dispatcher != null) dispatcher.forward(request, response);
		}
	}
	
	protected Date getDate(HttpServletRequest request, HttpServletResponse response) throws ParseException{
		String day= request.getParameter("day");
		String month=request.getParameter("month");
		String year=request.getParameter("year");
		
		String datetimeString=year+" " + month + " " + day;
		return DateUtil.convertStringToDateYYYYMMDD(datetimeString);
	}
	
	protected int getTitleBits(HttpServletRequest request, HttpServletResponse response) throws ParseException{
		String[] titles = request.getParameterValues("title");

		//storing what titles the user has marked through bitwise operation
		int titleBits = 0x00;
		if (titles != null) {
			Title title;
			for (int i = 0; i < titles.length; i++)	{
				String value=titles[i];
				if(!RegexUtil.isNullOrEmpty(value)){
					title=TitleUtil.getTitleByTitleName(value);
					if(title!=null){
						titleBits |= title.getTitleBit();
					}
				}
			}
			return titleBits;
		}
		return -1;
	}
}
